/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 正则规则集合
 */
export const patterns = {
  mobile: {
    // 手机号
    code: 3001,
    pattern: /^1[2-9]{1}[0-9]{1}\d{8}$/,
    message: '手机号码输入错误',
    tag: '手机号',
  },
  tel: {
    // 电话号码
    code: 3002,
    pattern: /^(0\d{2,3}(-|\s?))?[2-9]{1}\d{6,7}((-|\s?)\d{1,4})?$/,
    message: '电话号码输入错误',
    tag: '电话号码',
  },
  contact: {
    // 联系方式
    code: 30012,
    pattern: /^1\d{10}$|^(0\d{2,3}(-|\s?))?[2-9]{1}\d{6,7}((-|\s?)\d{1,4})?$/,
    message: '请输入正确的手机或固话',
    tag: '联系方式',
  },
};

interface CheckResult {
  code: number;
  message: string;
}

// 正则规则验证方法
export const patternCheck = (data: object, special = {}): CheckResult => {
  let result: CheckResult = { code: 0, message: '验证通过' };
  Object.keys(data).every((item) => {
    const rule = special[item] ||
      patterns[item] || {
        code: 11,
        message: `缺少对应的正则规则：${item}`,
      };
    const value = data[item] || '';
    const { pattern, message, tag } = rule;
    const isExact = !!`${value}`.match(pattern);
    if (!isExact && result.code === 0) {
      result = value
        ? rule
        : {
            code: 1001,
            message: value ? message : `${tag}不能为空`,
          };
    }
    return !!isExact;
  });
  return result;
};
